from PyQt5.QtWidgets import QDialog, \
    QVBoxLayout, \
    QLabel, \
    QLineEdit, QPushButton, QMessageBox

import os


class AlertDialog(QDialog):
    def __init__(self, window, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.field_dic = {}
        self.init_ui()
        self.edit = None
        self.window = window

    def init_ui(self):
        self.setWindowTitle("配置信息")
        self.resize(300, 200)

        layout = QVBoxLayout()

        form_data_list = [
            {"address": "结果存储地址"}
        ]

        file_object = open('config.text', mode='a+')
        for item in form_data_list:
            config = file_object.readline().strip()
            lab = QLabel()
            lab.setText(item["address"])
            edit = QLineEdit()
            edit.setText(config)
            edit.setFixedHeight(30)
            layout.addWidget(lab)
            layout.addWidget(edit)
            self.field_dic[item['address']] = edit
        file_object.close()

        btn = QPushButton("保存")
        btn.setFixedWidth(100)
        btn.clicked.connect(self.save_config)
        layout.addWidget(btn)
        layout.addStretch(1)
        self.setLayout(layout)

    def save_config(self):
        try:
            file_object = open('config.text', mode='w')
            for key, filed in self.field_dic.items():
                # 存储配置数据
                file_object.writelines(filed.text())
                if key == '结果存储地址':
                    self.window.destPath = filed.text()
                    os.listdir(filed.text())
            file_object.flush()
            file_object.close()
            self.close()
        except Exception as e:
            QMessageBox.warning(self,"错误",'地址错误！')
